package com.meihua.baoleyi.ui;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.meihua.baoleyi.R;
import com.meihua.baoleyi.base.BaseActivity;
import com.meihua.baoleyi.common.APIServer;
import com.meihua.baoleyi.common.MyApp;
import com.meihua.baoleyi.fragment.BaikeFragment;
import com.meihua.baoleyi.fragment.MainFragment;
import com.meihua.baoleyi.fragment.SonServiceFragment;
import com.meihua.baoleyi.fragment.WoDeFragment;
import com.meihua.baoleyi.utils.FileUtil;
import com.meihua.baoleyi.widget.NoScrollViewPager;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class MainActivity extends BaseActivity {
    @Bind(R.id.viewpager)
    NoScrollViewPager viewpager;
    //首页
    @Bind(R.id.sy_img)
    ImageView syImg;
    @Bind(R.id.shouye_lin)
    LinearLayout shouyeLin;
    //商城
    @Bind(R.id.shop_img)
    ImageView shopImg;
    @Bind(R.id.shop_lin)
    LinearLayout shopLin;
    //儿推服务
    @Bind(R.id.sonservice_img)
    ImageView sonserviceImg;
    @Bind(R.id.sonservice_lin)
    LinearLayout sonserviceLin;
    //百科知识
    @Bind(R.id.baike_img)
    ImageView baikeImg;
    @Bind(R.id.baike_lin)
    LinearLayout baikeLin;
    //我的
    @Bind(R.id.wd_img)
    ImageView wdImg;
    @Bind(R.id.wode_lin)
    LinearLayout wodeLin;

    @Bind(R.id.bottomLayout)
    LinearLayout bottomLayout;
    @Bind(R.id.fragmentContainerFrame)
    FrameLayout fragmentContainerFrame;

    private LinearLayout currentTab;
    private List<Fragment> fragment_list;
    private boolean isToWode = false;
    private MainFragment fragment1;
    private MainFragment fragment2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        init();
    }

    /**
     * 初始化View
     */
    private void init() {
        fragment_list = new ArrayList<>();
        fragment1 = MainFragment.newInstance(APIServer.HOME_GETSHOPLIST);
        fragment_list.add(fragment1);
        fragment2 = MainFragment.newInstance(APIServer.SHOP_GETSHOPLIST);
        fragment_list.add(fragment2);
        fragment_list.add(new SonServiceFragment());
        fragment_list.add(new BaikeFragment());
        fragment_list.add(new WoDeFragment());

        viewpager.setAdapter(new PagerAdapter(getSupportFragmentManager()));
        viewpager.setOffscreenPageLimit(fragment_list.size());
        isCheckpager();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (fragment1 != null) {
            fragment1.isShoppingCatEmpty();
        }
        if (fragment2 != null) {
            fragment2.isShoppingCatEmpty();
        }
    }

    private void isCheckpager() {
//        if (StringUtils.isStringNull(MyApp.getInstance().getUserTicket())) {
//            currentTab = wodeLin;
//            currentTab.setSelected(true);
//            viewpager.setCurrentItem(4);
//        } else {
            currentTab = shouyeLin;
            currentTab.setSelected(true);
            viewpager.setCurrentItem(0);
//        }
    }

    /**
     * launchMode为singleTask的时候，通过Intent启到一个Activity,如果系统已经存在一个实例，
     * 系统就会将请求发送到这个实例上，但这个时候，系统就不会再调用通常情况下我们处理请求数据的onCreate方法，
     * 而是调用onNewIntent方法
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        int intExtra = intent.getIntExtra("type", 0);
        if (intExtra == 1) {
            changeTab(wodeLin, 4); // 退出登录后跳到首页--我的
        } else if (intExtra == 4) {
//            changeTab(activity_lin, 2); // 我的--我参加的活动没数据，去活动首页逛逛
        }
    }

    private void changeTab(LinearLayout tab, int index) {
        currentTab.setSelected(false);
        currentTab = tab;
        currentTab.setSelected(true);
        viewpager.setCurrentItem(index);
    }

    @OnClick({R.id.shouye_lin, R.id.shop_lin, R.id.sonservice_lin, R.id.baike_lin, R.id.wode_lin})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.shouye_lin:
                changeTab(shouyeLin, 0);
                break;
            case R.id.shop_lin:
                changeTab(shopLin, 1);
                break;
            case R.id.sonservice_lin:
                changeTab(sonserviceLin, 2);
                break;
            case R.id.baike_lin:
                changeTab(baikeLin, 3);
                break;
            case R.id.wode_lin:
                isToWode = true;
                changeTab(wodeLin, 4);
                break;
        }
    }

    class PagerAdapter extends FragmentPagerAdapter {

        public PagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int arg0) {
            return fragment_list.get(arg0);
        }

        @Override
        public int getCount() {
            return fragment_list.size();
        }
    }

    private long count = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long detla = System.currentTimeMillis() - count;
            if (detla > 2000) {
                Toast.makeText(MainActivity.this, "再按一次退出", Toast.LENGTH_SHORT).show();
                count = System.currentTimeMillis();
                return true;
            } else {
                finish();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //相册
        if (requestCode == 1) {
            if (data == null || data.getData() == null) {
                return;
            }
            String[] pojo = {MediaStore.MediaColumns.DATA};
            Cursor cursor = getContentResolver().query(data.getData(), pojo, null, null, null);
            int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
            cursor.moveToFirst();
            String picPath = cursor.getString(columnIndex);
            ((WoDeFragment) fragment_list.get(fragment_list.size() - 1)).setAva(picPath);
        } else if (requestCode == 0) {//拍照
            ((WoDeFragment) fragment_list.get(fragment_list.size() - 1)).setAva(FileUtil.getUtil().SDPATH + "photo_release" + MyApp.getInstance().time + ".png");
        }
    }
}